package 力扣;

import com.sun.xml.internal.ws.encoding.RootOnlyCodec;

/**
 * @author yyq
 * @create 2022-04-21 14:46
 */
public class leetcode108 {
    public static void main(String[] args) {
        sortedArrayToBST(new int[]{0,1,2,3,4,5,6});
    }

    public static TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==1) return new TreeNode(nums[0]);
        int rootindex = nums.length/2;
        int rootval = nums[rootindex];
        TreeNode root = new TreeNode(rootval);
        // left代表左边界
        // right代表右边界
        int left = 0;
        int right = nums.length-1;
        AddNode(root,nums,left,right,rootindex);
        return root;
    }

    private static void AddNode(TreeNode root, int[] nums, int left, int right, int rootIndex) {
        // 递归结束条件
        if(left==right) return;
        // 该节点存在左子树
        if(left!=rootIndex){
            int rootLeftIndex = (rootIndex-left)/2+left;
            TreeNode rootleft= new TreeNode(nums[rootLeftIndex]);
            root.left=rootleft;
            //接下来对该节点继续构建其左右子树
            AddNode(rootleft,nums,left,rootIndex-1,rootLeftIndex);
        }
        // 该节点存在右子树
        if(right!=rootIndex){
            int rootRightIndex = (right + 1 - rootIndex)/2 + rootIndex;
            TreeNode  rootright=new TreeNode(nums[rootRightIndex]);
            root.right=rootright;
            //接下来对该节点继续构建其左右子树
            AddNode(rootright,nums,rootIndex+1,right,rootRightIndex);
        }
    }
}
